using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;


/*
* Introduction：    循环视图池单元格基类，提供单元格的基础功能和接口
* Version：         1.1
* Creator：         yixiang.hui
* Creation Time：   2025.9.3
*
* Last Editor：     yixiang.hui 
* Last Edit Time：  2025.9.3
* Note：            1.1版本优化了内存管理，添加了子单元格管理功能
*/

namespace Hyx.UIComponent
{
    public abstract class LoopViewPoolCell : MonoBehaviour
    {
        void Awake()
        {
            cacheRectTransform = GetComponent<RectTransform>();
            cacheLayoutElement = GetComponent<LayoutElement>();
            cacheObejct = gameObject;
            cacheTransform = transform;
            Init();
        }

        public virtual void OnStart()
        {
        }

        public abstract void Init();

        [HideInInspector]
        public LoopViewPool pool;

        [HideInInspector]
        public List<LoopViewPoolCell> childcells = new List<LoopViewPoolCell>();

        public virtual void Reset()
        {
            if (childcells.Count > 0)
            {
                foreach (var item in childcells)
                {
                    item.Reset();
                    pool.PutChild(item, item.childindex);
                }
            }
            childcells.Clear();
        }

        [HideInInspector]
        public RectTransform cacheRectTransform;

        [HideInInspector]
        public GameObject cacheObejct;

        [HideInInspector]
        public Transform cacheTransform;

        [HideInInspector]
        public LayoutElement cacheLayoutElement;

        [HideInInspector]
        public int childindex = -1;

        public virtual T GetChild<T>(int index) where T : LoopViewPoolCell
        {
            var childcell = pool.FetchChild<T>(index);
            childcell.childindex = index;
            childcell.cacheObejct.SetActive(true);
            childcell.cacheRectTransform.anchorMax = Vector2.up;
            childcell.cacheRectTransform.anchorMin = Vector2.up;
            childcell.cacheRectTransform.pivot = Vector2.up;
            childcell.cacheRectTransform.anchoredPosition = Vector2.zero;
            childcell.cacheRectTransform.localScale = Vector3.one;
            childcell.cacheTransform.SetParent(cacheTransform, false);
            childcells.Add(childcell);
            return childcell as T;
        }
    }
}